package com.cxs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxs.common.dto.FormDto;
import com.cxs.common.exception.APIException;
import com.cxs.entity.Table;
import com.cxs.mapper.TableMapper;
import com.cxs.service.ITableService;
import com.cxs.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.cxs.controller.base.BaseController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chaoxiaoshu
 * @since 2022-07-05
 */
@RestController
@RequestMapping("/sys/table")
public class TableController extends BaseController {

    @Autowired
    TableMapper tableMapper;

    @Autowired
    ITableService tableService;

    @PreAuthorize("hasAuthority('sys:table:list')")
    @PostMapping("/list")
    public IPage<Table> list(@RequestBody Map<String,Object> params) {
        QueryWrapper<Table> query = new QueryWrapper<>();
        Object permissionId = params.get("permissionId");
        if (permissionId != null) {
            query.eq("permission_id", permissionId.toString());
        }
        Page<Table> page = tableService.page(new Page<>(1, 10), query);

        return page;
    }

    @PreAuthorize("hasAuthority('sys:table:list')")
    @GetMapping("/options/{tableName}")
    public Map<String, Object> getOptions(@PathVariable String tableName) {
        Map<String, Object> map = new HashMap<>();
        List<FormDto.Option> options = tableMapper.getTableColumn(tableName);
        String jsonStr = JsonUtil.readJsonFile("/json/formAttr.json");
        JSONObject result = JSONObject.parseObject(jsonStr);
        JSONArray table = result.getJSONArray("table");
        List<FormDto> formDtoList = JSONObject.parseArray(table.toJSONString(), FormDto.class);

        formDtoList.forEach(formDto -> {
            if (formDto.getField().equals("field")) {
                formDto.setOptions(options);
            }
        });

        map.put("formAttr", formDtoList);
        return map;
    }

    @PreAuthorize("hasAuthority('sys:table:save')")
    @PostMapping("/save")
    public boolean save(@RequestBody Table table) {
        return tableService.save(table);
    }

    @PreAuthorize("hasAuthority('sys:table:update')")
    @PostMapping("/update")
    public boolean update(@RequestBody Table table) {
        return tableService.updateById(table);
    }

    @PreAuthorize("hasAuthority('sys:table:delete')")
    @PostMapping("/delete")
    public boolean delete(@RequestBody List<Long> ids) {
        if (ids.size() == 0) {
            throw new APIException("A0402", "id");
        }
        return tableService.removeByIds(ids);
    }

}
